var wineApp = wineApp || {};
wineApp.winedetail = (function() {

    var params = $.url().param();
    var pageSize = 8;
    var wineId = params["wineId"];
    var key_login_flag = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'login_flag';
    var resourceURL = wineApp.tool.getResourceURL();
    var countPerSet = wineApp.CONFIG.countPerSet;
    var addrId = '';
    var ammount = 0;
    var wineDetail = null;
    var initPage = function() {
        initWinInfo();
        //initComment();
        //initSpinbox();
        initEvent();
        //loadAddr();

    }

    var initEvent = function() {
        $(document).on('click', '.wine_jlshopcar', addShopcar);
        $(document).on('click', '.wine_jgshop', createOrder);
        //$(document).on('click', '.wine_sc', addFocus);
        /*
        $(document).on('click', '#wechat', function(event) {
            var url = "" +
                Wechat.share({
                    message: {
                        title: shopcar["wineName"],
                        description: "酒旅真棒",
                        mediaTagName: "不知道干嘛用的",
                        thumb: "https://mmbiz.qlogo.cn/mmbiz/ZPeUKc755PVTA2586EketRPmurNoBeuLpia4q3HW8TbvIv8U2KOY4MnUMvJBCbMPSEgsxqehsAfQibia0BCkKMR9w/0?wx_fmt=png",
                        media: {
                            type: Wechat.Type.WEBPAGE, // webpage
                            webpageUrl: "http://alcoholways.com/share/hj.html?id=" + wineId // webpage
                        }
                    },
                    scene: Wechat.Scene.TIMELINE // share to Timeline
                }, function() {
                    wineApp.tool.toastSuccess('发布成功');
                }, function(reason) {
                    console.log('error:%O', reason);
                    //alert("Failed: " + reason);
                })
        });
        */

    }


    var initImgSlider = function(imgList) {
        var height = wineApp.tool.getScreenWidth();
        wineApp.common.buildCarousel('#owl-demo', imgList, function(val) {
            var content = '<a href="#">' +
                '<img class="scale" src="' + resourceURL + '/' + val.imgid + '" width=100% height=' + height + '/>' +
                '</a>'
            return content;
        });
    }

    var addFocus = function() {
        var ajaxUrl = wineApp.CONFIG.API.focus;
        var key = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'userInfo.msg.platUser';
        var userInfo = wineApp.localStorage.get(key);
        if (userInfo == null) {
            window.location.href = '../login.html';
        }
        var loginUserId = userInfo.id;

        wineApp.ajax.post(ajaxUrl, {
            id: wineId,
            type: 1,
            userId: loginUserId,
            darenUserId: drId
        }, function(data) {
            if (data.st == 'ok') {
                wineApp.tool.toastSuccess('收藏成功!');
            }
        });
    }
    var checkByCount = function() {
        var num = parseInt($('#spin-value').val(), 10);
        if (num == 0) {
            //wineApp.tool.toastError("请选择数量!");
            layer.open({
                content: '请选择数量!',
                btn: '确定'
            });
            return false;
        }
        ammount = num * wineDetail.price * countPerSet;
        if (ammount != 3000) {
            //wineApp.tool.toastError("总价必须等于3000元");
            layer.open({
                content: '总价必须等于3000元',
                btn: '确定'
            });
            return false;
        }
        return true;
    }
    var createOrder = function() {
        //判断是否有登陆
        if (!wineApp.common.verifyLogin()) {
            return;
        }
        //判断是否选择了3000元的产品
        if (!checkByCount()) {
            return;
        }
        var obj = [{
            count: $('#spin-value').val(),
            prodid: wineId,
            ammount: ammount,
            wineName: wineDetail.title,
            wineImg: resourceURL + "/" + wineDetail.titleimg,
            winePrice: wineDetail.price,
            wineOverseasPrice: wineDetail.oprice,
            id: wineDetail.wineId
        }]
        wineApp.orderutil.createProdObjToStorage(obj, 'plandetail');
        window.location.href = 'order.html';
    }

    var loadAddr = function() {
        var ajaxUrl = wineApp.CONFIG.API.addresslist + '?userId=' + userInfo.platUser.id;
        wineApp.ajax.get(ajaxUrl, function(data) {
            if (data.st == 'ok') {
                $.each(data.msg, function(index, val) {
                    if (val.isDefault == "1") {
                        addrId = val.id;
                    }
                });
            }
        })
    }

    var initSpinbox = function() {
        $(document)
            .on('click', '.spin-minus', function() {
                var val = parseInt($('#spin-value').val(), 10);
                if (val <= 0) {
                    $('#spin-value').val(0);
                } else {
                    val = val - 1;
                    $('#spin-value').val(val);
                }
            })
            .on('click', '.spin-plus', function() {
                var val = parseInt($('#spin-value').val(), 10);
                if (val >= 9999) {
                    $('#spin-value').val(9999);
                } else {
                    val = val + 1;
                    $('#spin-value').val(val);
                }
            })
    }


    var initWinInfo = function() {
        var ajaxUrl = wineApp.CONFIG.API.winedetail;
        wineApp.ajax.post(ajaxUrl, {
            id: wineId
        }).done(onSuccess);
    }


    var shopcar = {};
    var onSuccess = function(data) {
        wineDetail = data.detail;
        var width = wineApp.tool.getScreenWidth();
        var wineImg = resourceURL + "/" + data.detail.titleimg + '!' + width + 'x' + width;
        var wineBaseInfo =
            '<dl>' +

            '<dd>' + data.detail.catname + data.detail.ctype +
            '<br><span>' + data.detail.title + '</span></dd>' +
            '</dl>'
        $('.wine_products_more').html(wineBaseInfo);
        //价格信息
        shopcar["wineImg"] = data.detail.titleimg;
        shopcar["wineName"] = data.detail.title;
        shopcar["winePrice"] = data.detail.price;
        shopcar["wineOverseasPrice"] = data.detail.oprice;
        shopcar["id"] = wineId;
        var price =
            '<ul>' +
            '<li>会员价：<b>￥' + data.detail.price + '</b><i>原价：￥' + data.detail.oprice + '</i></li>' +
            '<li>销 量：<b>' + data.detail.scount + '</b></li>' +
            '<li><label>数量(箱)：</label><a href="javascript:void(0)" class="bor_Rnone spin-minus">-</a><span><input type="text" class="bb_inpNO" value="1" maxlength="5" name="wineNum" id="spin-value" /> </span><a href="javascript:void(0)" class="bor_Lnone spin-plus">+</a></li>' +
            '</ul>';
        $('.wine_price').append(price);
        initSpinbox();
        //图文详情
        var desc = data.detail.note //.replace(/&nbsp;/ig, '');
        $('.wine_tuwenmore').html(desc);


        var imgList = _.concat(data.imgList)
        $.each(imgList, function(index, val) {
            var img = '<img src="' + resourceURL + '/' + val.imgid + '"></img>'
            $('.wine_tuwenmore').append(img);
        });

        initImgSlider(data.slideList);
        //酒类身份证

        // $('.wine_id').html(idCard);
        // //comment
        // //酒庄信息
        // $('#jzlogo').attr('src', resourceURL + data.msg.merchant.logoPicUrl + '!50x50')
        //     //$('#jzname').html(data.msg.merchant.name)
        // $('#jzlink').attr('href', 'jz_detail.html?drId=' + data.msg.merchant.userId);
        // $('#jzlink').html(data.msg.merchant.name)
    }
    var addShopcar = function() {
        if (!wineApp.common.verifyLogin()) {
            return;
        }
        var num = parseInt($('#spin-value').val(), 10);
        if (num == 0) {
            wineApp.tool.toastError("请选择数量!");
            return;
        }
        shopcar["num"] = num;
        var selectedProd = {
            prodid: shopcar.id,
            proname: shopcar.wineName,
            titleimg: shopcar.wineImg,
            num: shopcar.num,
            oprice: shopcar.wineOverseasPrice,
            price: shopcar.winePrice
        }
        var ajaxUrl = wineApp.CONFIG.API.cartadd;
        wineApp.ajax.post(ajaxUrl, { product: selectedProd })
            .done(function(data) {
                window.location.href = "gwc.html";
            });
        // var key = wineApp.tool.getKey("shopcar");
        // var shopcarHistory = wineApp.localStorage.get(key);
        // if ($.isEmptyObject(shopcarHistory)) {
        //     wineApp.localStorage.set(key, []);
        //     shopcarHistory = [];
        // };
        // var idx = -1;
        // //如果ID重复数量合并
        // $.each(shopcarHistory, function(index, val) {
        //     if (val.id == shopcar.id) {
        //         idx = index;
        //         shopcar.num = val.num + shopcar.num;
        //         return false;
        //     }
        // });
        // //wineApp.localStorage.set(key, [], true);
        // //wineApp.localStorage.set(key, [shopcar]);
        // if (idx != -1) {
        //     shopcarHistory[idx] = shopcar;
        //     wineApp.localStorage.set(key, [], true);
        //     wineApp.localStorage.set(key, shopcarHistory);
        // } else {
        //     wineApp.localStorage.set(key, [shopcar]);
        // }
        // var key_login_flag = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'login_flag';
        // var checkLogin = wineApp.localStorage.get(key_login_flag);
        // if (checkLogin !== "checked") {
        //     window.location.href = "../login.html?refURL=index.html";
        // } else {
        //     window.location.href = "gwc.html";
        // }
    }

    return {
        initPage: initPage
    }
})();

$(document).ready(function() {
    $('.wine_footer').remove();
    wineApp.common.initHeaderIcon(0, true);
    wineApp.winedetail.initPage();
});